package tralala.server.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import tralala.server.data.Cancion;

public class CancionJDO {

private PersistenceManager pm = null;
	
	
	public CancionJDO(){
		pm = DAO.getInstance().connect();
	}
	
	public void guardar(Cancion can){
		Transaction tx = pm.currentTransaction();
		try{
			tx.begin();
			pm.makePersistent(can);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
		    if (tx.isActive()) {
		        tx.rollback();
		    }
		}
	}
	
	public void borrar(Cancion can){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		pm.deletePersistent(can);
		tx.commit();
	}
	
	@SuppressWarnings("unchecked")
	public List<Cancion> get(String titulo, String artista){
		List<Cancion> listaCanciones = null;
		Transaction tx = pm.currentTransaction();
		try{
			tx.begin();
			Query query = pm.newQuery("SELECT FROM " + Cancion.class.getName() + " WHERE titulo == '" + titulo + "' & artista == '" + artista + "'");
			listaCanciones = (List<Cancion>)query.execute();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
		    if (tx.isActive()) {
		        tx.rollback();
		    }
		}
		
		return listaCanciones;
	}
	
	public List<Cancion> buscarPorTitulo(String titulo){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		Query query = pm.newQuery("SELECT FROM " + Cancion.class.getName() + " WHERE titulo == '" + titulo + "'");
		@SuppressWarnings("unchecked")
		List<Cancion> listaCanciones = (List<Cancion>) query.execute();
		tx.commit();
		
		return listaCanciones;
	}
	
	@SuppressWarnings("unchecked")
	public List<Cancion> buscarPorArtista(String artista){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		Query query = pm.newQuery("SELECT FROM " + Cancion.class.getName() + " WHERE artista == '" + artista + "'");
		List<Cancion> listaCanciones = (List<Cancion>) query.execute();
		tx.commit();
		return listaCanciones;
	}
	
	
	public List<Cancion> getCanciones(){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		Query query = pm.newQuery("SELECT FROM " + Cancion.class.getName());
		@SuppressWarnings("unchecked")
		List<Cancion> listaCanciones = (List<Cancion>) query.execute();
		tx.commit();
		
		return listaCanciones;
	}
	
	public Cancion get(String titulo){
		Cancion canc = null;
		Transaction tx = pm.currentTransaction();
		try{
			tx.begin();
			Query query = pm.newQuery("SELECT FROM " + Cancion.class.getName() + " WHERE titulo == '" + titulo + "'");
			query.setUnique(true);
			canc = (Cancion)query.execute();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
		    if (tx.isActive()) {
		        tx.rollback();
		    }
		}
		return canc;
	}
}